<template>
  
    <!-- 用户信息卡片 start -->
    <view class="user_card">
      

      <!-- 统计信息卡片 start -->
	  <view class="bg-white ss-p-b-20">
		  <view class="statistics_card_2" v-if="!state.isteam">
		    <view class="card_header">
		      <view class="title">团队数据</view>
		      <view class="switch_team">
		        <image :src="sheep.$url.cdn('/storage/default/20250318/fd6b875a4a737049ddedf1b2127574cc.png')" class="switch_icon"></image>
		        <span @click="switch_team_data">切换人员概况</span>
		      </view>
		    </view>
		  
		    <view class="stat_grid">
		      <view class="stat_item">
		        <view class="stat_title">团队人数<br />(累计)</view>
		        <view class="stat_value">{{state.data.team_count}}人</view>
		      </view>
		      <view class="stat_item">
		        <view class="stat_title">商务BD<br />(累计)</view>
		        <view class="stat_value">{{state.data.maker_total}}人</view>
		      </view>
		      <view class="stat_item">
		        <view class="stat_title">昨日新增<br />(团队团员)</view>
		        <view class="stat_value">{{state.data.yesterday_new}}人</view>
		      </view>
		      <view class="stat_item">
		        <view class="stat_title">今日新增<br />(团队团员)</view>
		        <view class="stat_value">{{state.data.today_new}}人</view>
		      </view>
		      <view class="stat_item">
		        <view class="stat_title">今日实付<br />(直推间推)</view>
		        <view class="stat_value">{{state.data.today_paid}}</view>
		      </view>
		      <view class="stat_item">
		        <view class="stat_title">今日佣金<br />(元)</view>
		        <view class="stat_value">{{state.data.today_commission}}</view>
		      </view>
		      <view class="stat_item">
		        <view class="stat_title">待结算<br />(待收货)</view>
		        <view class="stat_value">{{state.data.pending_commission}}</view>
		      </view>
		      <view class="stat_item">
		        <view class="stat_title">已结算<br />(累计)</view>
		        <view class="stat_value">{{state.data.settled_commission}}</view>
		      </view>
		     <!-- <view class="stat_item">
		        <view class="icon_block" style="background-color: #ffd700"></view>
		        <view class="stat_title">团队补贴</view>
		      </view>
		      <view class="stat_item">
		        <view class="icon_block" style="background-color: #1e90ff"></view>
		        <view class="stat_title">划拨明细</view>
		      </view>
		      <view class="stat_item">
		        <view class="icon_block" style="background-color: #1e90ff"></view>
		        <view class="stat_title">划拨</view>
		      </view> -->
		      <!-- <view class="stat_item">
		        <view class="icon_block" style="background-color: #1e90ff"></view>
		        <view class="stat_title">已签门店</view>
		      </view> -->
		      <view class="stat_item">
		        <view class="stat_title">营业额<br />(当日营收)</view>
		        <view class="stat_value">{{state.data.total_sales}}</view>
		      </view>
		      <view class="stat_item">
		        <view class="stat_title">门店数量<br />(累计)</view>
		        <view class="stat_value">{{state.data.store_count}}家</view>
		      </view>
		      <view class="stat_item">
		        <view class="stat_title">本地访客<br />(累计)</view>
		        <view class="stat_value">{{state.data.local}}人</view>
		      </view>
		      <view class="stat_item">
		        <view class="stat_title">消费人数<br />(累计)</view>
		        <view class="stat_value">{{state.data.consumer_count}}人</view>
		      </view>
		    </view>
		  </view>
		  
		  <!-- 统计信息卡片 end -->
		  
		  <view class="statistics_card" v-if="state.isteam">
		    <view class="card_header">
		      <view class="title">人员概况</view>
		      <view class="switch_team">
		        <image :src="sheep.$url.cdn('/storage/default/20250318/fd6b875a4a737049ddedf1b2127574cc.png')" class="switch_icon"></image>
		        <span @click="switch_team_data">切换团队数据</span>
		      </view>
		    </view>
		  
		    <view class="stat_grid" >
		      <view class="stat_item">
		        <view class="role_name">普通用户</view>
		        <view class="role_count">{{ state.data.user }}</view>
		      </view>
			  <view class="stat_item">
			    <view class="role_name">商务BD</view>
			    <view class="role_count">{{ state.data.maker}}</view>
			  </view>
			  <view class="stat_item">
			    <view class="role_name">商务BDM</view>
			    <view class="role_count">{{ state.data.leader }}</view>
			  </view>
			  <view class="stat_item">
			    <view class="role_name">街道服务商</view>
			    <view class="role_count">{{ state.data.short_partner }}</view>
			  </view>
			  <view class="stat_item">
			    <view class="role_name">区县代理</view>
			    <view class="role_count">{{ state.data.high_partner }}</view>
			  </view>
			  <view class="stat_item">
			    <view class="role_name">地市代理</view>
			    <view class="role_count">{{ state.data.founder }}</view>
			  </view>
		    </view>
		  </view>
		  <!-- 用户信息卡片 end -->
	  </view>
	  
	  <view style="height:20rpx;background:#F6F6F6"></view>
	  <!-- 树状组织架构 -->
	  <view class="ss-p-y-26 ss-p-x-34">
		  <view class="ss-flex ">
			  <image style="width:36rpx;height:36rpx" :src="sheep.$url.cdn('/storage/default/20250313/d8821a7629443f5d87db30d5b795711b.png')" ></image>
			  <view class="title ss-m-l-10">组织架构</view>
		  </view>
		  <view class="genealogy-tree ">
			  
			<scroll-view  :style="{width:'100vw',height:state.isteam?'830rpx':'650rpx'}" scroll-x="true" scroll-y="true" @scroll="" >
					  <view :style="'transform: translate(' + state.stv.offsetX*2 + 'rpx, ' + state.stv.offsetY*2 + 'rpx) scale(' + state.stv.scale + ')'" style="width:max-content" class="ss-p-r-50 container tree-content"
					      @touchstart="touchstartCallback" 
						  @touchmove="touchmoveCallback" 
						  @touchend="touchendCallback"
					  >
						  <treeList style="background:red"  :tree-data="treeData" :tree-first="true" :deep="1"/>
					  </view>
			</scroll-view>
			
		 </view>
	  </view>
    </view>

</template>

<script setup>
import { reactive,computed,ref, provide, nextTick, watch, getCurrentInstance, onMounted } from 'vue';
import {  } from '@dcloudio/uni-app';
import sheep from '@/sheep';
import treeList from './tree-list';
import { throttle } from 'lodash';
	const userStore = sheep.$store('user');
  
	let scale = ref(1); // 缩放倍率
    let timer = ref(null); // 节流定时器
    const instance = getCurrentInstance(); // 获取组件实例
    let treeConfig = ref({ // movable-view移动区域大小
        width: 0,
        height: 800
    })
	 const getDomInfo = (domID) => {
	        return new Promise((resolve, reject) => {
	            const bar = uni.createSelectorQuery().in(instance);
	            bar.select(domID).boundingClientRect(res => {
	                if (res) resolve(res);
	                else reject()
	            }).exec();
	        })
	    }
  
  
let state = reactive({
  isteam: true,
  data:{},
  timer:null,
  data:{},
  scale: 1, // 缩放比例
	 stv: {
	        offsetX: 120,
	        offsetY: 0,
	        zoom: false, // 是否缩放
	        distance: 0, // 两指距离
	        scale: 1 // 缩放倍数
	      },
		  startX:0,
		  startY:0,
		  touchStartEvent:0
});

// 组织数据 
const org_data = reactive([
  {
    role_name: '普通用户',
    count: 0,
  },
  {
    role_name: '商务BD',
    count: 0,
  },
  {
    role_name: '商务BDM',
    count: 0,
  },
  {
    role_name: '服务中心',
    count: 0,
  },
  {
    role_name: '区县代理',
    count: 0,
  },
  {
    role_name: '地市代理',
    count: 0,
  },
]);

const userInfo = computed(() => userStore.userInfo);
/* 触摸开始 */
    function touchstartCallback(e) {
      if (e.touches.length === 1) {
        let { clientX, clientY } = e.touches[0];
        state.startX = clientX;
        state.startY = clientY;
        state.touchStartEvent = e.touches;
      } else {
        let xMove = e.touches[1].clientX - e.touches[0].clientX;
        let yMove = e.touches[1].clientY - e.touches[0].clientY;
        let distance = Math.sqrt(xMove * xMove + yMove * yMove);
        state.stv.distance = distance;
        state.stv.zoom = true; // 缩放状态
      }
    }
    /* 触摸移动中 */
    function touchmoveCallback(e) {
      // 单指移动
      if (e.touches.length === 1) {
        if (state.stv.zoom) return; // 缩放状态，不处理单指
        let { clientX, clientY } = e.touches[0];
        let offsetX = clientX - state.startX;
        let offsetY = clientY - state.startY;
        state.startX = clientX;
        state.startY = clientY;
        let { stv } = state;
        stv.offsetX += offsetX;
        stv.offsetY += offsetY;
        stv.offsetLeftX = -stv.offsetX;
        stv.offsetLeftY = -stv.offsetLeftY;
        state.stv = stv;
      }
      // 双指缩放
      else {
        let xMove = e.touches[1].clientX - e.touches[0].clientX;
        let yMove = e.touches[1].clientY - e.touches[0].clientY;
        let distance = Math.sqrt(xMove * xMove + yMove * yMove);
        let distanceDiff = distance - state.stv.distance;
        let newScale = state.stv.scale + 0.005 * distanceDiff;
        state.stv.distance = distance;
        state.stv.scale = newScale;
      }
    }
    /* 触摸结束 */
    function touchendCallback(e) {
      if (e.touches.length === 0) {
        state.stv.zoom = false; // 重置缩放状态
      }
    }



// 树形结构数据
    let treeData = ref()

// 树状图数据
const get_org_tree = async () => {
	var type
	if(state.isteam){
		type='personal'
	}else{
		type='team'
	}
	const res = await sheep.$api.user.org.getTree({
		type,
	})
	treeData.value=[res.data.list]
	state.data=res.data.role_counts
	
	
	
	
	
	
};


// 切换团队数据 
const switch_team_data = async () => {
	state.isteam = !state.isteam;
	get_org_tree()
};

 /**
	     * 递归对树形结构添加节点
	     * @param {number | string} id 唯一键
	     * @param { Array } 树形结构数组
	     * @param { Object } obj 添加的数据
	     * */
	    const handleData = (id, data, obj) => {
	        data.forEach( (item,index) => {
	            if (item.id === id) {
					 if(item.children){
						var pos=item.children.findIndex(item=>item.id==-1)
						if(pos>-1){
							item.children.splice(pos,1)
						}
						console.log('kankkkkkkkkkkkkkkk',pos,item.children,)
					}
					 item.children? item.children.push(obj) : item.children = [obj]
	            } else {
	                if (item.children) {
	                    handleData(id, item.children, obj)
	                }
	            }
	        })
	        return data
	    }
		// 查看更多
		provide('showMore', async (parent) => {
			
			// 第几页
			var page=Math.ceil(parent.children.length/10)
			const res = await sheep.$api.user.org.getNext({
				parent_id:parent.id,
				page,
				list_rows:10,
			})
			
			var arr=res.data.data
			for(var i=0;i<arr.length;i++){
				handleData(parent.id, treeData.value, {
					...arr[i]
				})
			}
			if(parent.children.length<res.data.total){
				handleData(parent.id, treeData.value, {
				    id: -1, // 唯一键后续自行设置
				    name: '查看更多',
				})
			}
				
		})
		

 
    // 删除
    provide('delItem', (item) => {
		
        treeData.value = deleteNodeById(treeData.value, item.id);
		console.log('delItem后',treeData.value )
		
    })
	/**
	     * 添加
	     * @param { object } item 当前点击的对象
	     * @param { number } type 0添加子级，1添加兄弟，2添加父辈，3添加自己
	     * */
	provide('addItem', async (item, type) => {
		
		const res = await sheep.$api.user.org.getNext({
			parent_id:item.id,
			page:1,
			list_rows:10,
		})
		var arr=res.data.data
		
		// // 例子
		// var arr=[]
		// for(var i =0;i<5;i++){
		// 	arr.push({
		// 		avatar: "/static/img/default_avatar.png",
		// 		id: 1,
		// 		mobile: "18006785208",
		// 		nickname: "用户96uvu4j6",
		// 		role: "普通用户",
		// 		children_count: 7,
		// 		current_page: 1,
		// 		last_page: 1,
		// 		per_page: 10,
		// 		num:2,
		// 	})
		// }
		
		
			for(var i=0;i<arr.length;i++){
					handleData(item.id, treeData.value, {
					    ...arr[i]
					})
				
				
			}
			console.log('查看更多',item,res.data.total)
			if(item?.children?.length<res.data.total){
				handleData(item.id, treeData.value, {
				    id: -1, // 唯一键后续自行设置
				    name: '查看更多',
				})
			}
			
	        
	    })
		
		
		
		
	    onMounted(()=>{
			console.log('onMounted')
	        setTreeConfig()
			get_org_tree()
	    })
		
	    // 监听树形结构数据变化
	    watch(treeData,(newVal,oldVal)=>{
			console.log('触发')
	        setTreeConfig()
	    },{ 
		deep:true
		})
	    // 设置移动缩放大小
	    const setTreeConfig = () => {
	        nextTick(()=> {
	            setTimeout(()=>{
	                getDomInfo('.my-tree').then(res => {
						console.log('daxiao',res.height)
	                    Object.assign(treeConfig.value, {
	                        width: res.width / scale.value,
	                        height: res.height / scale.value,
	                    });
	                })
	            },100)
	        })
	    }
	   
	    /**
	     * 递归删除树形结构元素
	     * @param { Array } tree 树形结构数据
	     * @param { number | string } id 唯一键
	     * */
	    const deleteNodeById = (tree, targetId) => {
			console.log(tree, targetId)
	        for (let i = 0; i < tree.length; i++) {
	            const node = tree[i];
	            if (node.id === targetId) {
	                console.log('找到了',node);
	                // 使用 splice 删除节点
	                // tree.splice(i, 1);
					tree[i].children=[]
	                return tree; // 返回新的数组
	            }
	            if (node.children && node.children.length > 0) {
	                // 递归查找子节点
	                node.children = deleteNodeById(node.children, targetId);
	            }
	        }
	        return tree; // 没有找到目标节点，返回原数组
	    }





</script>

<style lang="less" scoped>
	.genealogy-tree {
	        position: relative;
	        overflow: hidden;
	
	        .tree-content {
	        }
	    }
// 用户信息卡片样式 start
.user_card {
  width: 100%;
  max-height:100vh;
  

  .user_header {
    background: linear-gradient(180deg, rgba(0, 108, 217, 0.8) 0%, rgba(0, 46, 131, 0.8) 100%);
    height: 250rpx;
    position: relative;
    border-radius: 0 0 50rpx 50rpx;

    .user_info {
      padding: 30rpx;
      display: flex;
      align-items: center;

      .avatar {
        width: 80rpx;
        height: 80rpx;
        border-radius: 50%;
        overflow: hidden;
        background-color: #fff;
        margin-right: 20rpx;

        image {
          width: 100%;
          height: 100%;
        }
      }

      .user_detail {
        .name {
          font-size: 30rpx;
          color: #fff;
          margin-bottom: 10rpx;
        }

        .role {
          font-size: 24rpx;
          color: #fff;
        }
      }
    }
  }

.bgGray{
	background:#EEF1F6;
	padding-bottom:30rpx;
}
.title {
        font-size: 28rpx;
        font-weight: bold;
		background: #085285;
		-webkit-background-clip: text;
		-webkit-text-fill-color: transparent;
		background-clip: text;
		text-fill-color: transparent;
      }
  .statistics_card {
    margin: 40rpx 30rpx 0;
    background: #D6E2F7;
    border-radius: 12rpx;
    padding: 30rpx;
    position: relative;
    z-index: 3;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
    .card_header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 30rpx;

      

      .switch_team {
        display: flex;
        align-items: center;
        font-size: 24rpx;
        color: #647BB0;

        .switch_icon {
          width: 24rpx;
          height: 18rpx;
          margin-right: 12rpx;
        }
      }
    }

    .stat_grid {
      display: flex;
      flex-wrap: wrap;
      justify-content: space-between;

      .stat_item {
        width: 33.33%;
        text-align: center;
        margin-bottom: 30rpx;

        .role_name {
          font-size: 26rpx;
          color: #647BB0;
          margin-bottom: 10rpx;
        }

        .role_count {
          font-size: 28rpx;
          font-weight: bold;
          color: #2378f7;
        }
        .stat_title {
          font-size: 24rpx;
          color: #647BB0;
          margin-bottom: 5rpx;
        }
        .stat_value {
          font-size: 28rpx;
          font-weight: bold;
          color: #2378f7;
        }
        .icon_block {
          width: 50rpx;
          height: 50rpx;
          margin: 0 auto 10rpx;
          border-radius: 8rpx;
          background-color: #ddd; // 默认背景色
        }
      }
    }
  }
}
// 用户信息卡片样式 end

.statistics_card_2 {
    margin: 40rpx 30rpx 0;
    background: #D6E2F7;
    border-radius: 12rpx;
    padding: 30rpx;
    position: relative;
    z-index: 3;
    box-shadow: 0px 0px 10rpx 0px rgba(0, 0, 0, 0.2);
  .card_header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30rpx;

    

    .switch_team {
      display: flex;
      align-items: center;
      font-size: 24rpx;
      color: #647BB0;

      .switch_icon {
        width: 24rpx;
        height: 18rpx;
        margin-right: 12rpx;
      }
    }
  }

  .stat_grid {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;

    .stat_item {
      width: 25%;
      text-align: center;
      margin-bottom: 20rpx;

      .stat_title {
        font-size: 24rpx;
        color: #647BB0;
        margin-bottom: 5rpx;
        line-height: 1.5;
      }

      .stat_value {
        font-size: 28rpx;
        font-weight: bold;
        color: #2378f7;
      }

      .icon_block {
        width: 50rpx;
        height: 50rpx;
        margin: 0 auto 10rpx;
        border-radius: 8rpx;
      }
    }
  }
}
</style>
